package utils_jwt

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"io/ioutil"
	"mall-portalv2/conf"
	"mall-portalv2/global"
	"net/http"
	"strings"
	"time"
)

type jiaChaoUser struct {
	UserId  int    `json:"user_id"`
	UserKey string `json:"user_key"`
	Alias   string `json:"alias"`
	PictUrl string `json:"pict_url"`
}

type jiaChaoUserResult struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Result  jiaChaoUser `json:"result"`
}

var (
	prefix = "jiachao_key_"
)

func GetJiaChaoInfo(token string) (jiaChaoUserResult, error) {
	result := jiaChaoUserResult{}

	type SendBody struct {
		Token     string `json:"token"`
		Sign      string `json:"sign"`
		Timestamp int64  `json:"timestamp"`
	}

	nowTime := time.Now().Unix()

	send := SendBody{
		Token:     token,
		Sign:      CreateSign(token, fmt.Sprintf("%d", nowTime), conf.Config.Jiachao.AuthKey),
		Timestamp: nowTime,
	}

	fn := clientPost(conf.Config.Jiachao.AuthApi, send)

	questResult, err := fn()
	if err != nil {
		global.Log.Error("请求家超用户中间件出错", zap.Error(err))
		return result, err
	}

	sendResult := jiaChaoUserResult{}
	json.Unmarshal(questResult, &sendResult)
	return result, nil
}

func clientPost(url string, in interface{}) func() ([]byte, error) {
	var body []byte
	var err error

	c := make(chan struct{}, 1)
	go func() {
		defer close(c)

		var res *http.Response

		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
		client := &http.Client{Transport: tr}
		jsonBody, _ := json.Marshal(in)
		res, err = client.Post(url, "application/json", strings.NewReader(string(jsonBody)))

		if err != nil {
			return
		}

		defer res.Body.Close()
		body, err = ioutil.ReadAll(res.Body)
	}()
	return func() ([]byte, error) {
		<-c
		return body, err
	}
}
